'use strict';

app.controller('transactionAnalysisCtrl',[ '$scope','$filter','$modal','transactionAnalysisService','toaster','utilService', function($scope,$filter,$modal,transactionAnalysisService,toaster,utilService) {
    $scope.date = new Date();
    //$scope.date.setTime($scope.date.getTime()-24*60*60*1000);
    $scope.analysis={
        analysisType:0,
        date:$scope.date ,
        startTime : $scope.date,
        endTime : $scope.date
    }

    $scope.max=new Date($scope.date);
    $scope.min=getPreMonth($filter("date")(new Date($scope.date), "yyyy-MM-dd"),3);

    $scope.legend = [ "下单笔数","下单人数","下单金额","支付笔数","支付人数","支付金额"];
    $scope.item = [ '--','--','--','--','--','--','--','--','--','--','--','--' ];
    $scope.data = [
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    ];

    //查询交易分析数据
    $scope.query=function(){
        if($scope.analysis.analysisType==0){
            $scope.analysis.date=$filter("date")($scope.analysis.date, "yyyy-MM-dd");
        }else if($scope.analysis.analysisType==1){
            $scope.analysis.date=$filter("date")($scope.analysis.date, "yyyy-MM-dd");
        }else if($scope.analysis.analysisType==2){
            $scope.analysis.startTime = $filter("date")($scope.analysis.startTime, "yyyy-MM-dd");
            $scope.analysis.endTime = $filter("date")($scope.analysis.endTime, "yyyy-MM-dd");
        }
        transactionAnalysisService.findTransactionAnalysis($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.analysisData = result.data.transactionAnalysis;
                    $scope.item=result.data.transactionInfo.item;
                    $scope.data=result.data.transactionInfo.data;
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break
            }
        });
    };
    $scope.query();

    //导出交易分析统计数据
    $scope.exportAllData=function(){
        openModal("确定要导出已查询出的记录吗？" +
            "(导出时间跟导出数据量的大小有关，请耐心等待)");
        function openModal(msg){
            utilService.modal($modal, $scope, {
                title:"温馨提示",
                controller:"exportTransactionCtrl",
                message:msg,
                data: $scope.analysis
            });
        }
    }



    //导出交易分析详情
    $scope.openExportDate=function(){
        var modalInstance = $modal.open({
            templateUrl: 'tpl/data/export_transaction_data.html',
            controller: 'exportTransactionDataCtrl',
            scope: $scope,
            resolve: {
                deps: ['uiLoad',
                    function (uiLoad) {
                        return uiLoad.load([
                            'css/content-css/data/data.css',
                        ]);
                    }
                ]
            }
        });
    }
}]);

app.controller('exportTransactionCtrl', ['$scope','$filter', '$modalInstance','modalData','transactionAnalysisService',
    function($scope,$filter, $modalInstance,modalData,transactionAnalysisService) {
        $scope.modal = modalData;
        $scope.param = modalData.data;
        $scope.AllowToReport=true;
        $scope.ok=function(){
            if(!$scope.AllowToReport){
                return;
            }
            $scope.AllowToReport=false;
            if($scope.analysis.analysisType==0){
                $scope.analysis.date=$filter("date")($scope.analysis.date, "yyyy-MM-dd");
            }else if($scope.analysis.analysisType==1){
                $scope.analysis.date=$filter("date")($scope.analysis.date, "yyyy-MM-dd");
            }else if($scope.analysis.analysisType==2){
                $scope.analysis.startTime = $filter("date")($scope.analysis.startTime, "yyyy-MM-dd");
                $scope.analysis.endTime = $filter("date")($scope.analysis.endTime, "yyyy-MM-dd");
            }
            transactionAnalysisService.exportTransactionData($scope);
            $modalInstance.dismiss('success');
        }
        //取消弹窗
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }
]);

//导出数据模态框Controller
app.controller('exportTransactionDataCtrl', ['$scope', '$modalInstance','transactionAnalysisService','toaster',
    function($scope, $modalInstance,transactionAnalysisService,toaster) {
        $scope.data={
            exportType:0,
        };

        //导出
        $scope.AllowToReport=true;
        $scope.exportData=function(){
            if(!$scope.AllowToReport){
                return;
            }
            $scope.AllowToReport=false;
            transactionAnalysisService.exportData($scope);
            $modalInstance.dismiss('success');
        }
        //取消弹窗
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }
]);

app.directive('line', function() {
    return {
        scope: {
            id: "@",
            legend: "=",
            item: "=",
            data: "="
        },
        restrict: 'E',
        template: '<div style="height:400px;width: 100%;"></div>',
        replace: true,
        link: function($scope, element, attrs, controller) {
            var option = {
                // 提示框，鼠标悬浮交互时的信息提示
                tooltip: {
                    trigger: 'axis',
                    textStyle:{
                        color:'#fff'
                    },
                    fontSize:12,
                    padding:15,
                    show:true,
                    formatter: function(params) {
                        var res='';
                        var date='';
                        var ordersCount='';
                        var ordersUserCount='';
                        var ordersMoney='';
                        var payOrdersCount='';
                        var payUserCount='';
                        var payMoney='';
                        for(var i=0;i<params.length;i++){
                            date=params[0].name+'</br>';
                            if(params[i].seriesIndex==0){
                                ordersCount=params[i].seriesName+":"+params[i].data+'单'+'</br>';
                            }else if(params[i].seriesIndex==1){
                                ordersUserCount=params[i].seriesName+":"+params[i].data+'人'+'</br>';
                            }else if(params[i].seriesIndex==2){
                                ordersMoney=params[i].seriesName+":￥"+params[i].data+'</br>';
                            }else if(params[i].seriesIndex==3){
                                payOrdersCount=params[i].seriesName+":"+params[i].data+'单'+'</br>';
                            }else if(params[i].seriesIndex==4){
                                payUserCount=params[i].seriesName+":"+params[i].data+'人'+'</br>';
                            }else if(params[i].seriesIndex==5){
                                payMoney=params[i].seriesName+":￥"+params[i].data+'</br>';
                            }
                        }
                        res=date+ordersCount+ordersUserCount+ordersMoney+payOrdersCount+payUserCount+payMoney;
                        return res
                    }
                },
                // 图例
                legend: {
                    data: $scope.legend
                },
                // 横轴坐标轴
                xAxis: [{
                    type: 'category',
                    silent:true,
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: $scope.item,

                }],
                // 纵轴坐标轴
                yAxis: [{
                    axisLine: {
                        show: false
                    },
                    splitLine: {
                        show:false,
                        lineStyle: {
                            type: 'dotted'
                        }
                    },
                    type: 'value'
                }],
                // 数据内容数组
                series: function(){
                    var serie=[];
                    for(var i=0;i<$scope.legend.length;i++){
                        var item = {
                            name : $scope.legend[i],
                            type: 'line',
                            symbol: 'circle',
                            smooth: true,
                            data: $scope.data[i]
                        };
                        serie.push(item);
                    }
                    return serie;
                }()
            };
            var myChart = echarts.init(document.getElementById($scope.id),'macarons');
            myChart.setOption(option);

            $scope.$watch('item',function(){
                option.xAxis=[{type: 'category', data: $scope.item}];
                var serie=[];
                for(var i=0;i<$scope.legend.length;i++){
                    var item = {
                        name : $scope.legend[i],
                        type: 'line',
                        symbol: 'circle',
                        smooth: true,
                        data: $scope.data[i]
                    };
                    serie.push(item);
                }
                option.series=serie;
                myChart.clear();
                myChart.setOption(option,true);
            })
        }
    };
});

function getPreMonth(date,num) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2=parseInt(month);

    for(var i=0;i<num;i++){
        month2 = parseInt(month2) - 1;
        if (month2 == 0) {
            year2 = parseInt(year2) - 1;
            month2 = 12;
        }
    }

    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}